var arr02 = [{
    "time": "2018-05-14"
  },
  {
    "time": "2018-05-12"
  },
]

var arr = [];


// pages/daka/daka.js
var app = getApp();
var util = require('../../utils/util.js');
var glo = require('../../utils/global.js');
var bibleData = require('../../utils/bible.js')
var oldbook = "";
var newbook = "";
var dkflag = true;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dakaObj: [],
    oData: [],
    isedit: false, //是否编辑
    selTime: false, //时间筛选
    allSelBool: false, //全选确定
    timeStart: '',
    timeEnd: '',
    closeFixedShow: false,
    selRadio: '',
    filterCount: 1,
    noPunch: false,
    pageCount: 8,
    noMore: false,
    fxpyqts: decodeURI("%E7%82%B9%E5%87%BB%E2%80%98%E6%84%9F%E8%B0%A2%E4%B8%BB%E2%80%99%E5%AF%B9%E8%AF%9D%E6%A1%86%E5%8F%91%E9%80%81%E2%80%987%E2%80%99%E8%8E%B7%E5%8F%96%E8%AF%BB%E7%BB%8F%E6%89%93%E5%8D%A1%E6%88%90%E7%BB%A9%E9%93%BE%E6%8E%A5%E5%88%86%E4%BA%AB%E6%9C%8B%E5%8F%8B%E5%9C%88%E3%80%82"),
    gxz: decodeURI("%E6%84%9F%E8%B0%A2%E4%B8%BB"),
    dk: decodeURI('%E6%89%93%E5%8D%A1')
  },
  radioChange: function(e) {
    var val = e.detail.value;
    this.setData({
      selRadio: val,
      timeStart: '',
      timeEnd: ''
    });
  },
  closeFixed: function() {
    this.setData({
      closeFixedShow: false,
      selRadio: ''
    });
  },
  dateChange01: function(e) {
    var val = e.detail.value;
    this.setData({
      timeStart: val,
      selRadio: ''
    });
    console.log(this.data.timeStart)
  },
  dateChange02: function(e) {
    var val = e.detail.value;
    this.setData({
      timeEnd: val,
      selRadio: ''
    });
  },
  allSel: function() {
    var that = this,
      userInfo = this.data.userInfo;
    if (!this.data.allSelBool) {
      var arr = this.data.dakaObj;
      arr.forEach(function(objA, i) {
        if (arr[i]) {
          arr[i].selDelbool = true;
          var arrA = arr[i].arrData;
          arrA.forEach(function(objB, j) {
            var arrB_data = arrA[j].data;
            var arrB_selData = arrA[j].selData;
            arrB_data.forEach(function(ojbC, k) {
              arrB_selData[k] = 'del';
            });
          });
        }
      });
      this.setData({
        dakaObj: arr,
        allSelBool: true,
      });
    } else {
      wx.showModal({
        title: '您确定删除选中的' + decodeURI('%E6%89%93%E5%8D%A1')+'记录吗？',
        content: '',
        success: function(res) {
          if (res.confirm) {
            wx.request({
              url: glo.https + '/person/punch_del',
              data: {
                punch: userInfo.punch,
                userid: userInfo.userId,
              },
              success: function(res2) {
                console.log(res2);
                if (res2.data === true) {
                  userInfo.punch = '';
                  wx.setStorageSync('userInfo', userInfo);
                  that.setData({
                    dakaObj: [],
                    allSelBool: false,
                    isedit: false
                  });
                }
              }
            });
          }
        }
      });

    }
  },
  changDateSel: function(e) {
    var arr = this.data.dakaObj;
    var dateIndex = e.target.dataset.dateindex;
    var type = e.target.dataset.type;
    if (type == 'sel') {
      arr[dateIndex].selDelbool = true;
    } else {
      arr[dateIndex].selDelbool = false;
    }

    var selArr = arr[dateIndex].arrData;
    selArr.forEach(function(item, i) {
      var data = item.data;
      var selData = item.selData;
      data.forEach(function(its, index) {
        if (type == 'sel') {
          selData[index] = 'del'
        } else if (type == 'back')
          selData[index] = ''
      });
    });

    this.setData({
      dakaObj: arr
    });
  },
  timeListSel: function(e) {

  },
  delfn: function(e) {
    var that = this;
    var index = e.target.dataset.dateindex;
    var arr = this.data.dakaObj;
    var selArr = arr[index].arrData;
    var selArr_new = [];
    var delArr = [];
    var userInfo = this.data.userInfo;
    var time = arr[index].time;

    wx.showModal({
      title: '您确定删除选中的' + decodeURI('%E6%89%93%E5%8D%A1')+'记录吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          selArr.forEach(function(item, i) {
            var selArr_data = selArr[i].data;
            var selArr_selData = selArr[i].selData;
            var bookId = item.bookId;
            var newArr = [];
            var newSel = [];
            selArr_selData.forEach(function(ite, j) {
              if (ite !== 'del') {
                newArr.push(selArr_data[j]);
                newSel.push(selArr_selData[j]);
              } else {
                delArr.push(`;#${time}-${bookId}-${selArr_data[j]}#`);
              }
            });

            selArr[i].data = newArr;
            selArr[i].selData = newSel;
            if (newArr.length > 0) {
              selArr_new.push(selArr[i]);
            }
          });

          arr[index].data = selArr_new;
          arr[index].selDelbool = false;
          if (selArr_new.length == 0) {
            arr.splice(index, 1);
          }
          if (delArr.length !== 0) {
            for (let k = 0; k < delArr.length; k++) {
              userInfo.punch = userInfo.punch.replace(delArr[k], '');
            }
            let newPunch = delArr.join('');
            wx.request({
              url: glo.https + '/person/punch_del',
              data: {
                punch: newPunch,
                userid: userInfo.userId,
              },
              success: function(res2) {
                console.log(res2);
                if (res2.data === true) {
                  wx.setStorageSync('userInfo', userInfo);
                }
              }
            });
          }
          that.setData({
            dakaObj: arr
          });
        }
      }
    });
  },
  oneSel: function(e) {
    if (this.data.isedit === false) {
      return;
    }

    var arr = this.data.dakaObj;
    var index = e.target.dataset.index;
    var selArr = e.target.dataset.selarr;
    var path = e.target.dataset.path;
    var day = path[0];
    var book = path[1];
    var selData = arr[day].arrData[book].selData;

    selData.length = selArr.length;

    if (selData[index] == "del") {
      selData[index] = "";
    } else {
      selData[index] = "del";
    }

    var dateArr = arr[day].arrData;
    var bool = false;
    for (var i = 0; i < dateArr.length; i++) {
      if (dateArr[i].selData && dateArr[i].selData != undefined) {
        bool = dateArr[i].selData.some(function(item, i) {
          return item == 'del'
        });
      }

      if (bool) {
        break;
      }
    }
    arr[day].selDelbool = bool;

    this.setData({
      dakaObj: arr
    });
  },
  toggleEdit: function() {
    var bool = this.data.isedit;
    var allSelBool = this.data.allSelBool;

    var arr = this.data.dakaObj;
    arr.forEach(function(objA, i) {
      if (arr[i]) {
        arr[i].selDelbool = false;
        var arrA = arr[i].arrData;
        arrA.forEach(function(objB, j) {
          var arrB_data = arrA[j].data;
          var arrB_selData = arrA[j].selData;
          arrB_data.forEach(function(ojbC, k) {
            arrB_selData[k] = '';
          });
        });
      }
    });
    this.setData({
      dakaObj: arr,
      allSelBool: false,
      isedit: !bool
    });
  },
  openTimeSel: function() {
    /*
    var bool = this.data.selTime;
    this.setData({
      selTime: !bool
    });

    */
    this.setData({
      closeFixedShow: true
    });

  },
  timeToTimestamp: function(v) {
    if (v === '') {
      return;
    }
    var date = new Date(v);
    return Date.parse(date);
  },
  dateFilter: function(e) {
    var that = this,
      selRadio = this.data.selRadio,
      obj = this.data.oData,
      filterArr = [],
      start = this.timeToTimestamp(this.data.timeStart),
      end = this.timeToTimestamp(this.data.timeEnd),
      punch = this.data.userInfo.punch;
    if (start === undefined && end === undefined && selRadio === '') {
      return;
    }

    if (start !== undefined || end !== undefined) {
      obj.forEach(function(item, index) {
        let time = that.timeToTimestamp(item.time);
        if (time >= start && time <= end) {
          filterArr.push(item);
        }
      });
    }
    if (selRadio !== '') {
      let now = Date.parse(new Date()),
        tStamp,
        day = 86400000;
      if (selRadio === 'week') {
        tStamp = now - (day * 7);
      } else {
        tStamp = now - (day * 30);
      }
      obj.forEach(function(item, index) {
        let time = that.timeToTimestamp(item.time);
        if (time >= tStamp && time <= now) {
          filterArr.push(item);
        }
      });
    }
    that.setData({
      dakaObj: filterArr,
      selRadio: '',
      closeFixedShow: false,
      filterCount: filterArr.length
    });
  },
  openShare: function(e) { //改
    var that = this;
    var time = e.currentTarget.dataset.time;
    console.log(time);
    if (dkflag) {
      dkflag = false;
      app.getUserInfo(function(userInfo) {
        console.log(JSON.stringify(userInfo));
        wx.request({
          url: glo.https + '/share/recordData',
          data: {
            openid: userInfo.wxId,
            userid: userInfo.userId,
            date: time
          },
          success: function(res) {

            that.setData({
              isPop: true
            });
            dkflag = true;
          }
        })
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();
    var bibleRead = wx.getStorageSync('bibleRead');
    var that = this;
    oldbook = bibleData.oldbooks;
    newbook = bibleData.newbooks;
    wx.setNavigationBarTitle({
      title: '我的' + decodeURI('%E6%89%93%E5%8D%A1'),
    })
    app.getUserInfo(function(userInfo) { //改      
      that.data.userInfo = userInfo;
      console.log(JSON.stringify(userInfo))
      var punch = that.data.userInfo.punch;
      var dianzanList = that.data.userInfo.dianzanList; //改
      if (punch === '') {
        that.setData({
          noPunch: true
        });        
        return;
      }

      var punchArr01 = punch.replace(/#/g, "").split(';').slice(1);

      var punchArr_0102 = [];
      punchArr01.forEach(function(item, index) {
        let mArr=item.split('-');
        console.log(mArr)
        punchArr_0102.push({
          time: item.slice(0, 10),
          text: mArr[3] + '-' + mArr[4],
          bookId: mArr[3],
          chapterId: mArr[4]
        });      
       
        punchArr_0102.sort(function(a, b) { //时间排序
          var t01 = new Date(a.time);
          var t02 = new Date(b.time);
          return t02 - t01;
        });
      });
     
      var punchArr_02 = [];
      //筛选时间
      for (var i = 0; i < punchArr_0102.length; i++) {
        var time = punchArr_0102[i].time;
        var isHas = false;
        for (var j = 0; j < punchArr_02.length; j++) {
          if (punchArr_02[j].time == time) {
            punchArr_02[j].data.push(punchArr_0102[i]);
            punchArr_02[j].data.sort(function(a, b) {
              return a.bookId - b.bookId
            });
            isHas = true;
          }
        }
        if (!isHas) {
          punchArr_02.push({
            time: time,
            selDelbool: false,
            data: [punchArr_0102[i]]
          });
        }
      }

      //筛选章节	 
      punchArr_02.forEach(function(item) {
        item.arrData = [];
        item.data.forEach(function(obj, index) {
          var bookId = obj.bookId
          var isHasBID = false;
          item.arrData.forEach(function(objA, inx) {
            if (objA.bookId == bookId) {
              isHasBID = true;
              item.arrData[inx].data.push(obj.chapterId);
              item.arrData[inx].data.sort(function(a, b) {
                return a - b;
              })
            }
          });
          if (!isHasBID) {
            if (!isNaN(bookId)) {
              if (bookId > 39) {

                var bookName = newbook[bookId - 40].bookName
              } else {
                var bookName = oldbook[bookId - 1].bookName
              }
              item.arrData.push({
                tit: bookName,
                bookId: bookId,
                selData: [],
                data: [obj.chapterId]
              })
            } else {
              console.log("bookId不是数字！！！！")
            }

          }
        });
      });
      if (dianzanList != null && dianzanList.length > 0) { //改
        if (punchArr_02 != null && punchArr_02.length > 0) {
          for (var i = 0; i < punchArr_02.length; ++i) {
            for (var ii = 0; ii < dianzanList.length; ++ii) {
              if (punchArr_02[i].time == dianzanList[ii].dktime) {
                var dcnt = 0;
                if (dianzanList[ii].dianzancnt != null && dianzanList[ii].dianzancnt != '') {
                  dcnt = dianzanList[ii].dianzancnt;
                }
                punchArr_02[i].dianzancnt = dcnt;
              }
            }
          }
        }

      }
      var pageCount = that.data.pageCount,
        page_punchArr = [];

      for (let p = 0; p < pageCount; p++) {
        if (punchArr_02[p] !== undefined) {
          page_punchArr.push(punchArr_02[p]);
        } else {
          that.setData({
            noMore: true
          });
          break;
        }
      }
      that.setData({
        dakaObj: page_punchArr,
        oData: punchArr_02,
        pageCount: pageCount + 8
      });
    
    }, '1');

  },
  share_qx: function() {
    this.setData({
      isPop: false
    });
  },
  lower: function() {
    var that = this,
      oData = this.data.oData,
      dataLength = this.data.oData.length,
      pCount = this.data.pageCount,
      newArr = [];
    if (this.data.noMore) {
      return;
    }

    for (let i = 0; i < pCount; i++) {
      if (oData[i] !== undefined) {
        newArr.push(oData[i]);
      } else {
        that.setData({
          noMore: true
        });
        break;
      }
    }
    this.setData({
      dakaObj: newArr,
      pageCount: pCount + 8
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showLoading({
      title: '加载中',
      mask: false
    });
    setTimeout(function(){
      wx.hideLoading();
    },1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  },
  hideLoad: function() {
    this.share_qx();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function() {

  }
})